const ChatAPI = {}


ChatAPI.person = [
    { name: 'Alice', online: true },
    { name: 'Bob', online: false },
    { name: 'Helen', online: false },
    { name: 'Jimmy', online: true }
]

const statusCallbacks = new Map()

var  intervalTimer = undefined

ChatAPI.subscribeToFriendStatus = function (name, cb) {
    if(!intervalTimer){
       intervalTimer =  setInterval(() => {
           console.log("ChatAPI interval scheduling")
            var index = (Math.floor(new Date().getTime() * Math.random())) % 4
            var person = ChatAPI.person[index]
            person.online = !person.online
            triggerPersonOnlineChange(person.name)
            
        }, 2500);
        triggerPersonOnlineChange(name)
    }
    statusCallbacks.set(name,cb)
}

function triggerPersonOnlineChange(name){
    if (statusCallbacks.has(name)) {
        statusCallbacks.get(name)(ChatAPI.person[ChatAPI.person.findIndex((v, i) => v.name === name)].online)
    }
}

ChatAPI.unsubscribeToFriendStatus = function (name) {
    if (statusCallbacks.has(name))
        statusCallbacks.delete(name)
}
export default ChatAPI